package com.jz.community.moduleshoppingguide.neighbor.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.donkingliang.imageselector.utils.ImageSelector;
import com.donkingliang.imageselector.utils.ImageSelectorUtils;
import com.gyf.barlibrary.ImmersionBar;
import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.base.ImageBrowserActivity;
import com.jz.community.basecomm.utils.eventbus.AppEvent;
import com.jz.community.basecomm.utils.eventbus.EventConfig;
import com.jz.community.moduleshoppingguide.R;
import com.jz.community.moduleshoppingguide.R2;
import com.jz.community.moduleshoppingguide.neighbor.bean.PublishTypeBean;
import com.jz.community.moduleshoppingguide.neighbor.bean.UploadImagesBean;
import com.jz.community.moduleshoppingguide.neighbor.presenter.PublishMessagePresenter;
import com.jz.community.moduleshoppingguide.neighbor.ui.PublishMsgView;
import com.jz.community.moduleshoppingguide.neighbor.ui.adapter.ImagePickerAdapter;
import com.jz.community.moduleshoppingguide.neighbor.ui.adapter.PublishTypeAdapter;
import com.qmuiteam.qmui.util.QMUIKeyboardHelper;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.github.rockerhieu.emojicon.EmojiconEditText;
import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import top.zibin.luban.Luban;

public class PublishMessageActivity extends BaseMvpActivity<PublishMsgView.View, PublishMessagePresenter> implements PublishMsgView.View, ImagePickerAdapter.OnRecyclerViewItemClickListener {

    @BindView(R2.id.publish_message_back)
    ImageView publishMessageBack;
    @BindView(R2.id.publish_message_title)
    TextView publishMessageTitle;
    @BindView(R2.id.publish_message_enter)
    TextView publishMessageEnter;
    @BindView(R2.id.publish_message_toolbar)
    Toolbar publishMessageToolbar;
    @BindView(R2.id.publish_message_edit)
    EmojiconEditText publishMessageEdit;
    @BindView(R2.id.publish_message_number)
    TextView publishMessageNumber;
    @BindView(R2.id.publish_message_number_rl)
    RelativeLayout publishMessageNumberRl;
    @BindView(R2.id.publish_message_tips_rv)
    RecyclerView publishMessageTipsRv;
    @BindView(R2.id.publish_message_tips_rl)
    RelativeLayout publishMessageTipsRl;
    @BindView(R2.id.publish_message_link_tv)
    TextView publishMessageLinkTv;
    @BindView(R2.id.publish_message_link_edit)
    EditText publishMessageLinkEdit;
    @BindView(R2.id.publish_message_link_delete)
    ImageView publishMessageLinkDelete;
    @BindView(R2.id.publish_message_link_rl)
    LinearLayout publishMessageLinkRl;
    @BindView(R2.id.publish_message_img_rv)
    RecyclerView publishMessageImgRv;
    @BindView(R2.id.publish_message_scroll)
    NestedScrollView publishMessageScroll;

    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;

    private CompositeDisposable compositeDisposable;


    private ArrayList<String> selImageList; //当前选择的所有图片
    private int maxImgCount = 9;               //允许选择图片最大数

    private ImagePickerAdapter adapter_img;

    private int maxEditLength = 150;

    private boolean canCommit = false;

    private boolean isCompress = false;

    private ArrayList<String> luBanPathList = new ArrayList<>();

    private List<PublishTypeBean.EmbeddedBean.ContentBean> tips_list;

    private PublishTypeAdapter adapter_tips;

    private String tip = "";

    private int oldPosition = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getContentView() {
        return R.layout.module_shoppingguide_activity_publish_message;
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    protected PublishMessagePresenter createPresenter() {
        return new PublishMessagePresenter(this);
    }

    @Override
    protected void initView() {
        super.initView();
        ImmersionBar.with(this)
                .titleBar(publishMessageToolbar)
                .statusBarDarkFont(true, 0.2f)//当白色背景状态栏遇到不能改变状态栏字体为深色的设备时，解决方案
                .init();

        publishMessageTitle.setText("发表动态");

        publishMessageNumber.setText("0" + "/" + maxEditLength);
    }

    @Override
    protected void initDatas() {
        initImgs();
        initTips();

        publishMessageEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                int length = s.length();
                if (length < maxEditLength) {
                    publishMessageNumber.setTextColor(getResources().getColor(R.color.font_gary_999));
                    if (length > 0) {
                        canCommit = true;
                        publishMessageEnter.setBackgroundResource(R.drawable.border_publish_red);
                        publishMessageEnter.setEnabled(true);
                    } else {
                        if (selImageList.size() > 0) {
                            canCommit = true;
                            publishMessageEnter.setBackgroundResource(R.drawable.border_publish_red);
                            publishMessageEnter.setEnabled(true);
                        } else {
                            canCommit = false;
                            publishMessageEnter.setBackgroundResource(R.drawable.border_publish_gray);
                            publishMessageEnter.setEnabled(false);
                        }

                    }
                    publishMessageNumber.setText(length + "/" + maxEditLength);
                } else {
                    publishMessageNumber.setTextColor(getResources().getColor(R.color.home_red));
                    showNormal("最多输入" + maxEditLength + "字");
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        Observable.just("1")
                .delay(600, TimeUnit.MILLISECONDS)//延时1秒弹出输入框
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {

                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);

                    }

                    @Override
                    public void onNext(String s) {
                        InputMethodManager inputManager = (InputMethodManager) publishMessageEdit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                        assert inputManager != null;
                        inputManager.showSoftInput(publishMessageEdit, 0);

                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {

                    }
                });

        mPresenter.initTips();

    }


    private void initImgs() {
        selImageList = new ArrayList<>();
        adapter_img = new ImagePickerAdapter(this, selImageList, maxImgCount);
        adapter_img.setOnItemClickListener(this);

        publishMessageImgRv.setLayoutManager(new GridLayoutManager(this, 3));
        publishMessageImgRv.setNestedScrollingEnabled(false);
        publishMessageImgRv.setHasFixedSize(true);
        publishMessageImgRv.setAdapter(adapter_img);
    }

    private void initTips() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(mActivity, LinearLayoutManager.HORIZONTAL, false);
        publishMessageTipsRv.setHasFixedSize(true);
        publishMessageTipsRv.setFocusable(false);
        publishMessageTipsRv.setLayoutManager(layoutManager);
        adapter_tips = new PublishTypeAdapter(R.layout.module_shoppingguide_item_publish_tips, tips_list);
        adapter_tips.openLoadAnimation(BaseQuickAdapter.ALPHAIN);//加载动画
        publishMessageTipsRv.setAdapter(adapter_tips);

        adapter_tips.setOnItemClickListener((adapter, view, position) -> {
            if (oldPosition == -1) {
                //进来未选择标签
                tip = adapter_tips.getData().get(position).getId();
                adapter_tips.getData().get(position).setSelect(true);
                adapter_tips.notifyDataSetChanged();
                oldPosition = position;
            } else {
                //已经选择过标签
                boolean isSelect = adapter_tips.getData().get(position).isSelect();

                if (oldPosition != position) {
                    adapter_tips.getData().get(oldPosition).setSelect(false);
                    adapter_tips.getData().get(position).setSelect(true);
                    tip = adapter_tips.getData().get(position).getId();
                } else {
                    if (isSelect) {
                        adapter_tips.getData().get(position).setSelect(false);
                        tip = "";
                    } else {
                        adapter_tips.getData().get(position).setSelect(true);
                        tip = adapter_tips.getData().get(position).getId();
                    }
                }

                oldPosition = position;
                adapter_tips.notifyDataSetChanged();
            }


        });

    }

    @SuppressLint("CheckResult")
    private void luBanWithRx(final List<String> photos) {
        if (!isCompress) {
            //如果没有压缩
            Flowable.just(photos)
                    .observeOn(Schedulers.io())
                    .map(list -> Luban.with(mActivity).load(list).get())
                    .doOnSubscribe(subscription -> showLoading())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(list -> {
                        for (File file : list) {
                            luBanPathList.add(file.getAbsolutePath());
                        }
                        upLoadImages(luBanPathList);
                        isCompress = true;
                    });
        } else {
            //已经压缩过了
            showLoading();
            upLoadImages(luBanPathList);
        }

    }

    private void upLoadImages(ArrayList<String> luBanPathList) {
        ArrayList<File> files = new ArrayList<>();
        File file;
        for (int i = 0; i < luBanPathList.size(); i++) {
            file = new File(luBanPathList.get(i));
            files.add(file);
        }
        mPresenter.upLoadImage(files);

    }

    @Override
    public void setTipsData(PublishTypeBean entity) {
        if (null != entity.get_embedded().getContent()) {
            tips_list = entity.get_embedded().getContent();

            if (tips_list.size() > 0) {
                publishMessageTipsRl.setVisibility(View.VISIBLE);
                adapter_tips.setNewData(tips_list);
            } else {
                publishMessageTipsRl.setVisibility(View.GONE);
            }
        } else {
            publishMessageTipsRl.setVisibility(View.GONE);
        }

    }

    @Override
    public void tipsError(String msg) {
        publishMessageTipsRl.setVisibility(View.GONE);

    }

    @Override
    public void UploadSuccess(UploadImagesBean entity) {
        if (null != entity.getImages() && entity.getImages().size() > 0) {
            List<String> images_up = entity.getImages();
            if (null != images_up && images_up.size() > 0) {
                StringBuilder images_string = new StringBuilder();
                for (int i = 0; i < images_up.size(); i++) {
                    images_string.append(images_up.get(i));
                    images_string.append(",");
                }

                String sContent = publishMessageEdit.getText().toString();
                mPresenter.publishMessage(images_string.substring(0, images_string.length() - 1), sContent, tip);
            }
        }


    }

    @Override
    public void UploadError(String msg) {
        showNormal("图片上传失败");
    }

    @Override
    public void publishSuccess() {
        dismissLoading();
        showNormal("发布成功!");
        EventBus.getDefault().post(new AppEvent(EventConfig.REFRESH_MINE_CIRCLE, 1));
        finish();

    }

    @Override
    public void publishError(String msg) {
        dismissLoading();
        showNormal("发布失败");

    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                //打开选择,本次允许选择的数量
                ImageSelector.builder()
                        .useCamera(true) // 设置是否使用拍照
                        .setSingle(false)  //设置是否单选
                        .setMaxSelectCount(9) // 图片的最大选择数量，小于等于0时，不限数量。
                        .setSelected(images) // 把已选的图片传入默认选中。
                        .setViewImage(true) //是否点击放大图片查看,，默认为true
                        .start(this, REQUEST_CODE_SELECT); // 打开相册
                break;
            default:
                //打开预览
                Intent intent = new Intent(this, ImageBrowserActivity.class);
                intent.putStringArrayListExtra("Key_ImageList", (ArrayList<String>) adapter_img.getImages());
                intent.putExtra("Key_CurrentPosition", position);
                intent.putExtra("isFromFile", 1);
                startActivity(intent);
                break;

        }

    }

    @Override
    public void onDeleteClick(View view, int position) {
        showDeleteDialog(position);

    }

    ArrayList<String> images = null;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && requestCode == REQUEST_CODE_SELECT) {
            images = data.getStringArrayListExtra(ImageSelectorUtils.SELECT_RESULT);
            if (images != null) {
                selImageList.clear();
                selImageList.addAll(images);
                adapter_img.setImages(selImageList);
                if (selImageList.size() > 0) {
                    canCommit = true;
                    publishMessageEnter.setBackgroundResource(R.drawable.border_publish_red);
                    publishMessageEnter.setEnabled(true);
                } else {
                    canCommit = false;
                    publishMessageEnter.setBackgroundResource(R.drawable.border_publish_gray);
                    publishMessageEnter.setEnabled(false);
                }
            }
        }
    }

    private void showDeleteDialog(final int position) {
        new MaterialDialog.Builder(mActivity)
                .title("提示")
                .content("是否确认删除图片?")
                .positiveText("确认")
                .negativeText("取消")
                .negativeColor(ContextCompat.getColor(this,R.color.negative_color))
                .positiveColor(ContextCompat.getColor(this,R.color.positive_color))
                .onPositive((dialog, which) -> {
                    //Publish 展示界面删除该图片
                    selImageList.remove(position);
                    //向Grid图片选择时，删除该图片
                    images.remove(position);
                    adapter_img.setImages(selImageList);

                    dialog.dismiss();
                })
                .onNegative((dialog, which) -> dialog.dismiss())
                .show();
    }

    private void showQuitDialog() {
        new MaterialDialog.Builder(mActivity)
                .title("提示")
                .content("是否退出编辑?")
                .positiveText("确认")
                .negativeText("取消")
                .negativeColor(ContextCompat.getColor(this,R.color.negative_color))
                .positiveColor(ContextCompat.getColor(this,R.color.positive_color))
                .onPositive((dialog, which) -> {
                    finish();
                    dialog.dismiss();
                })
                .onNegative((dialog, which) -> dialog.dismiss())
                .show();
    }

    private void addDisposable(Disposable disposable) {
        if (compositeDisposable == null) {
            compositeDisposable = new CompositeDisposable();
        }
        compositeDisposable.add(disposable);
    }

    private void dispose() {
        if (compositeDisposable != null) {
            compositeDisposable.dispose();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dispose();
    }

    @OnClick(R2.id.publish_message_back)
    public void backClick(View view) {
        if (canCommit) {
            showQuitDialog();
        } else {
            QMUIKeyboardHelper.hideKeyboard(publishMessageEdit);
            finish();
        }
    }

    @OnClick(R2.id.publish_message_enter)
    public void enterClick(View view) {
        if (canCommit) {
            //提交数据
            if (null != images && images.size() > 0) {
                //存在图片
                ArrayList<String> paths = new ArrayList<>();
                for (int i = 0; i < images.size(); i++) {
                    paths.add(images.get(i));
                }
                luBanWithRx(paths);
            } else {
                //只有文字
                showLoading();
                String sContent = publishMessageEdit.getText().toString();
                mPresenter.publishMessage("", sContent, tip);
            }
        }

    }


}
